package com.cloud.common.support;

import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * List转为Map使用的辅助类
 *
 * @author fengwenjin
 */
public class ListMapper<T> {
    private List<T> list;
    private Map<Object, T> map;

    public ListMapper(List<T> list, Function<T, Object> keyFunction) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        this.list = list;
        this.map = new HashMap<>();
        list.forEach(bean -> {
            if (bean != null) {
                map.putIfAbsent(keyFunction.apply(bean), bean);
            }
        });
    }

    public List<T> getList() {
        return list;
    }

    public T get(Object key) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return map.get(key);
    }
}
